importScripts('underscore.js');
console = {};
console.log = function () {
    obj = {'msg': 'console', 'args': []};
    _.each(arguments, function (arg) {
        obj.args.push(JSON.stringify(arg));
    });
    postMessage(obj);
};

var name = '';	// symbol wierzcholka
var graph = {};
var d = {};		// lista bezposrednich polaczen
var D = {};
var nexthops= {};


var do_init = function (pname, pgraph) {
    console.log('DO_INIT', pname, 'graph',pgraph);
	graph = _.clone(pgraph);
    d = _.clone(graph[pname]);
    d[pname] = 0;
    //D = _.clone(d);
    //D[pname] = 0;
    name = pname;
};

var do_start = function(){
	bellmanFord(graph, name, name);
}

onmessage = function (e) {
    if (e.data.msg == 'init') {
        do_init(e.data.name, e.data.graph);
    }else if (e.data.msg == 'start'){
        do_start();
    } else if (e.data.msg == 'get_final_state'){
        console.log('GET FINAL STATE', name, D);
        postMessage({
            'msg': 'finished',
            'name': name,
            'paths': D,
			'nexthops': nexthops
        })
    }
};

bellmanFord = function (g, fromIndex, toIndex) {
	if (!g.hasOwnProperty(fromIndex)){
		console.log('fromIndex does not exist in graph');
		return;
	}
	if (!g.hasOwnProperty(toIndex)){
		console.log('toIndex does not exist in graph');
		return;
	}
	
	// INITIALIZATION
	var d = {};	// vertexes weights
	var pred = {};	// predecessors
	for (var v in g){
		if (g.hasOwnProperty(v)) {
			 d[v] = null;
			 pred[v] = null;
		}
	}
	d[fromIndex] = 0;
	// PROCESSING
	for (var i in g){		// iterate i times											V
		for (var u in g){							// current vertex u					E
			if (g.hasOwnProperty(u)) {
				for (var v in g[u]){				// edge (v - neighbour vertex)		E
					if (g[u].hasOwnProperty(v)) {
						if (d[u]!=null){
							if ((d[v]==null) || (d[v]>d[u]+g[u][v])){
								d[v] = d[u]+g[u][v];
								pred[v] = u;
							}
						}
					}
				}
			}
		}
		
	}
	
	console.log(name, 'd=',_.clone(d));		// copy of d
	//console.log(name, 'pred=', _.clone(pred));	// copy of pred
	D = _.clone(d);
	nexthops = _.clone(pred);
	
	postMessage({
        'msg': 'computation_finished'
    });
}